package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;

import com.jackrain.clouddata.oms.dao.SaleDao;

import com.jackrain.clouddata.oms.dao.TransferDao;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.tlock.RedisReentrantLock;
import com.jackrain.nea.web.query.QueryEngine;
import com.jackrain.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;
/*
created by tangzhipeng on 2107/8/16
 */
@Component("com.jackrain.clouddata.sys.Listenter.TransferMessageProcess")
@Slf4j
public class TransferMessageProcess implements MessageProcess {

    @Override
    public void process(Object paramObject, String tag) throws Exception{
        TransferDao transferDao = ApplicationContextHandle.getBean(TransferDao.class);

        JSONArray paramArray = JSONArray.parseArray(JSON.toJSONString(paramObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
        try {
            if (paramArray != null && paramArray.size() > 0) {
                insertitem(paramArray, tag, transferDao);
            }
        }catch (Exception e){
            throw e;
        }
    }

    private void insertitem(JSONArray jsonArray,String tag,TransferDao transferDao) throws Exception {
        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        for (int i =0;i< jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONObject mainJson = jsonObject.getJSONObject("value");
            JSONArray itemArray = jsonObject.getJSONArray("item");
            //获取主表名称
            String mainName = jsonObject.getString("name");
            try{
                transferDao.insert(mainJson,itemArray,clientId,mainName);
                WebUtils.CallInterface(clientId,"OMS_M_TRANSFER",tag,jsonObject);
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }

}
